import json
from branca.element import Element

from PyQt5.QtWebEngineWidgets import QWebEnginePage

def add_customjs(map_object):
    my_js = f"""{map_object.get_name()}.on("click",
             function (e) {{
                var data = `{{"coordinates": ${{JSON.stringify(e.latlng)}}}}`;
                console.log(data)}});"""

    e = Element(my_js)
    html = map_object.get_root()
    html.script.get_root().render()
    # Insert new element or  JS
    html.script._children[e.get_name()] = e

    return map_object

class MapWebEnginePage(QWebEnginePage):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

    def javaScriptConsoleMessage(self, level, msg, line, sourceID):
        print(msg)  # Check js errors
        if 'coordinates' in msg:
            self.parent.handleConsoleMessage(msg)
